<!--
    group: 发票管理
    name: 重开票列表
    item: 重开票查询-子组件
-->
<template>
  <div>
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper" style="margin-bottom: 10px">
      <a-form layout="inline">
        <a-row :gutter="24" style="margin-top: 10px">
          <a-col :md="6" :lg="6" :xl="7" :xxl="4">
            <a-form-item label="企业名称">
              <a-input placeholder="请输入" v-model="filterList.entName" />
            </a-form-item>
          </a-col>
          <a-col :md="6" :lg="6" :xl="7" :xxl="4">
            <a-form-item label="法人">
              <a-input placeholder="请输入" v-model="filterList.lisenceLegal" />
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="10">
              <span class="table-page-search-submitButtons">
                <a-button type="primary" icon="search" @click="handleSearch">查询</a-button>
                <a-button style="margin-left: 10px" icon="reload" @click="handleReset">重置</a-button>
                <a @click="handleToggleSearch" style="margin-left: 8px">
                  {{ toggleSearchStatus ? '收起' : '展开' }}
                  <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                </a>
              </span>
          </a-col>
        </a-row>
        <div class="table-page-search-wrapper" v-show="toggleSearchStatus">
          <a-row :gutter="24">
            <a-col :md="6" :lg="6" :xl="7" :xxl="4">
              <a-form-item label="发票类型">
                <a-select  placeholder="请选择" v-model="filterList.taxType">
                  <a-select-option :value="''"> 请选择 </a-select-option>
                  <a-select-option :value="1">增值税专用发票</a-select-option>
                  <a-select-option :value="2">增值税普通发票</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :lg="6" :xl="7" :xxl="4">
              <a-form-item label="发票材质">
                <a-select  placeholder="请选择" v-model="filterList.taxMedium">
                  <a-select-option :value="''"> 请选择 </a-select-option>
                  <a-select-option :value="1">纸质</a-select-option>
                  <a-select-option :value="2">电子</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </div>

    <a-table bordered
             :loading="loading"
             :pagination="false"
             :rowKey="row => row.id"
             :columns="columns"
             :data-source="tableData"
             :row-selection="rowSelection"
             :scroll="{x:800}"
    >
      <!--发票类型 1-专票 2-普票-->
      <span slot="taxType" slot-scope="text,record">
        <!--taxMedium  1纸质 2电子-->
        <span :class="text === 1 ? 'd' : 'c'" style="margin-right: 5px">
          {{{1:'专票',2:'普票'}[text] || ''}}
        </span>
        <!-- 开票类型 1-传统票 2-数电票 3-混合票  -->
        <template v-if="record.ticketType == 1">
          <span :class="record.taxMedium === 1 ? 'a' : 'b'">
            {{{1:'纸质',2:'电子'}[record.taxMedium] || ''}}
          </span>
          <span v-if="record.taxMedium === 2 && record.imageType" class="doc" style="margin-left: 5px;">
            {{ record.imageType }}
          </span>
        </template>
        <span v-if="record.ticketType == 2" class="g">数电发票</span>
      </span>

      <!--状态-->
      <span slot="bizStatus" slot-scope="text,record">
        <a-tag :color="statusInfo.kstatusColor[text]">
          {{statusInfo.kstatusLabel[text]}}
        </a-tag>
      </span>

      <!--操作-->
      <span slot="action" slot-scope="text,record">
        <span v-if="record.bizStatus == 305">
          <a @click="paymentOther(record.payOrder)">支付</a>
          <a-divider type="vertical" />
        </span>
        <span v-if="record.bizStatus == 304">
          <a class="red" @click="invitationValidation(record.id)">邀请验证</a>
          <a-divider type="vertical" />
        </span>
        <!--纸质  确认寄送 , 电子 下载发票-->
        <span v-if="record.bizStatus == 307 && record.taxMedium == 1">
          <a class="red" @click="confirmDelivery(record.id)">确认寄送</a>
          <a-divider type="vertical" />
        </span>
        <span v-if="record.bizStatus == 310 && record.taxMedium == 2 && record.invoiceUrl">
          <a class="red" @click="invoiceDownload(record.invoiceUrl)">下载发票</a>
          <a-divider type="vertical" />
        </span>
        <span v-if="record.bizStatus != 303">
          <a @click="toDetails(record.id)">详情</a>
        </span>
      </span>
    </a-table>

    <div style="margin-top: 10px;">
      <a-button v-if="this.businessStatus == 305" type="primary" @click="batchPaymentFun">批量支付</a-button>
      <a-button v-if="this.businessStatus == 304" type="primary" @click="batchValidation">批量验证</a-button>
    </div>

    <a-pagination
      v-model="page.currentPage"
      :page-size-options="['5', '10', '20']"
      :show-total="total => `共 ${total} 条`"
      :total="page.totalCount"
      show-size-changer
      :page-size="page.pageSize"
      @showSizeChange="onSizeChange"
      @change="onPageChange"
    >
    </a-pagination>

    <!--确认寄送（发送成功），邀请验证-->
    <ModalCurrency :config="undoConfig" @fatherMethod="fatherMethod" />

    <!--批量验证-->
    <a-modal
      :width="800"
      :footer="null"
      v-model="invitationVisible"
    >
      <h3>验证邀请</h3>
      <p>我们将向下列用户发送发票认证，请确认发送对象！</p>

      <a-table bordered
               :pagination="false"
               :columns="verificationColumns"
               :data-source="verificationList"
               :scroll="{y:300}"
      >
      </a-table>
      <p style="text-align: center;margin-top: 20px;">
        <a-button class="btnsLarge" type="primary" @click="next">下一步</a-button>
      </p>
    </a-modal>

  </div>
</template>

<script>
import { getTaxInvoiceList,getConfirmDelivery,getTaxInvoiceCheckSendSms,getVerification,getTaxReopenTicketCheck } from '@/api/invoiceAdminister'
import ModalCurrency from '@views/invoice/common/modalCurrency.vue'
import status from '@/utils/invoicingStatus'
import * as Utils from '@/utils/util'
export default {
  name: 'invoiceReopenItem',
  components:{ ModalCurrency },
  props: ['businessStatus'],
  data(){
    return{
      statusInfo:status,
      toggleSearchStatus: false,
      filterList: {},
      loading: false,  //表格加载
      //表格分页
      page: {
        currentPage: 1, // 当前页
        pageSize: 10, // 每页显示条数
        totalPage: 0, // 总页数
        totalCount: 0, // 总条数
        params: {}, // 查询参数对象
        list: [], // 数据
      },
      tableData: [],
      columns: [
        {
          title: '订单编号',
          dataIndex: 'id',
          width: 100,
          align: 'center'
        },
        {
          title: '开票公司',
          dataIndex: 'taxTitle',
          ellipsis: true,
          width: 200,
          align: 'center'
        },
        {
          title: '企业负责人',
          dataIndex: 'lisenceLegal',
          ellipsis: true,
          width: 120,
          align: 'center'
        },
        {
          title: '发票类型',
          dataIndex: 'taxType',
          width: 150,
          scopedSlots: {customRender: 'taxType'},
          ellipsis: true,
          align: 'center'
        },
        {
          title: '提交时间',
          dataIndex: 'createTime',
          width: 180,
          align: 'center'
        },
        {
          title: '状态',
          dataIndex: 'bizStatus',
          scopedSlots: {customRender: 'bizStatus'},
          width: 120,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: {customRender: 'action'},
          align: 'center',
          fixed:'right',
          width: 240
        },
      ],
      selectedRowKeys: [],  //批量发布数据

      undoConfig:{
        width: '500px',  //modal宽度
        visible: false,    //modal展示状态
        modalTitle: '',
        title: '',     //标题
        subTitle: '',     //副标题
        content: '',  //内容
        okText: '确定撤销',    //确定文字
        okType: 'danger',    //确定类型
        cancleText: '暂不撤销',    //取消文字
        cancleType: 'default',    //取消类型
        source: 1,    //来源  ''发送成功  1撤销并删除 2邀请验证 3确认寄送 4删除草稿
      },

      invitationVisible:  false,   //邀请验证
      verificationList: [],
      testArr: [],  //
      verificationColumns: [
        {
          title: '公司法人',
          dataIndex: 'lisenceLegal',
          width: 150,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '法人实名手机号',
          dataIndex: 'legalPhone',
          width: 150,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '售票公司',
          dataIndex: 'entName',
          width: 150,
          ellipsis: true,
          align: 'center'
        },
        {
          title: '发票金额',
          dataIndex: 'amount',
          customRender: (text, record) => {
            return Math.round(text * 100) / 10000 + '元'
          },
          width: 150,
          ellipsis: true,
          align: 'center'
        },
      ]

    }
  },
  computed: {
    rowSelection() {
      return {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRows;
        },
      };
    },
  },
  mounted() {
    this.getTableData()
  },
  methods:{
    //查询展开收起
    handleToggleSearch(){
      this.toggleSearchStatus = !this.toggleSearchStatus;
    },
    //查询
    handleSearch(){
      this.page.currentPage = 1;
      this.getTableData();
    },
    //重置
    handleReset(){
      this.page.currentPage = 1;
      this.filterList = {};//清空查询条件
      this.getTableData();//重置列表
    },
    //选择页数
    onPageChange(newPage) {
      this.page.currentPage = newPage;
      this.getTableData()
    },
    // 页面变化
    onSizeChange(current, newSize) {
      this.page.pageSize = newSize;
      this.getTableData()
    },
    //详情
    toDetails(id){
      this.$router.push({
        path: '/invoice/invoiceRecord',
        query:{
          bizId: id,
          invoiceType: '重开票'
        }
      })
    },
    fatherMethod(config){
      //确定撤销
      this.$nextTick(()=>{
        this.undoConfig.visible = false;
      })
    },
    //邀请验证
    invitationValidation(id){
      let ids = [];
      ids.push(id)
      this.InvoiceCheckSendSms(ids);
    },
    //批量验证
    batchValidation(){
      if (this.selectedRows.length > 0){
        this.verificationList = this.selectedRows;
        this.testArr = this.reorganize('id',this.selectedRowKeys);
        this.invitationVisible = true;
      }else{
        this.$message.warning('合并核验选中数据不能为空');
        return false;
      }
    },
    next(){
      this.InvoiceCheckSendSms(this.testArr);
      this.invitationVisible = false;
    },
    //验证接口
    InvoiceCheckSendSms(ids){
      let params = {};
      params.data = {
        ids:ids,
      }
      getTaxReopenTicketCheck(params).then(res => {
        if (res.success) {
          this.$nextTick(()=>{
            this.undoConfig = {
              width: '500px',  //modal宽度
              visible: true,    //modal展示状态
              modalTitle: '邀请验证',
              title: '发送成功！',     //标题
              subTitle: '',     //副标题
              content: '请提示法人收到短信后，及时完成验证！',  //内容
              okText: '确定',    //确定文字
              okType: 'primary',    //确定类型
              cancleText: '',    //取消文字
              cancleType: '',    //取消类型
              source: '',   //来源
            }
          });
          this.getTableData();
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    //支付
    paymentOther(id){
      let arr = [];
      arr.push(id)
      this.paymentInvoice(arr);
    },
    //批量支付
    batchPaymentFun(){
      let arr = this.reorganize('payOrder',this.selectedRowKeys);
      if (this.selectedRowKeys.length > 0){
        this.paymentInvoice(arr);
      }else {
        this.$message.warning('合并支付选中数据不能为空');
        return false;
      }
    },
    //支付接口
    paymentInvoice(arr){
      let key = 'paymentInvoice'
      Utils.Storage.set(key,{orderNo: arr});
      // console.log(Utils.Storage.get('paymentInvoice'))
      this.$router.push({
        path: '/myAccount/accountManage',
        query:{
          po:key
        }
      });
    },
    //确认寄送
    confirmDelivery(id){
      getConfirmDelivery(id).then(res => {
        if (res.success) {
          this.$nextTick(()=>{
            this.undoConfig = {
              width: '500px',  //modal宽度
              visible: true,    //modal展示状态
              modalTitle: '',
              title: '发送成功！',     //标题
              subTitle: '',     //副标题
              content: '',  //内容
              okText: '确定',    //确定文字
              okType: 'primary',    //确定类型
              cancleText: '',    //取消文字
              cancleType: '',    //取消类型
              source: '',    //来源
            }
          })
          this.getTableData();
        }else{
          this.$message.warning(res.message);
        }
      })
    },
    //下载发票
    invoiceDownload(url){
      let data = url;
      //从链接上截取文件名
      let name = "发票";

      fetch(data).then((res) => {
        res.blob().then((blob) => {
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          a.download = name;
          a.click()
          window.URL.revokeObjectURL(url)
        })
      })
    },
    //首次获取表格数据
    getTableData(){
      this.loading = true;
      let params = {};
      params.data = this.filterList;
      params.data.status = 3;  // 1 新开票 2 退票 3 退票-错票
      params.data.bizStatus = this.businessStatus;

      params.pageNo = this.page.currentPage;
      params.pageSize = this.page.pageSize;

      getTaxInvoiceList(params).then(res => {
        if (res.success) {
          const data = res.result || {};
          // 赋值表格数据
          this.tableData = data.records || [];
          // 赋值总条数
          this.page.totalCount = data.total || 0;
          this.loading = false;
        }else{
          this.$message.warning(res.message)
        }
      })
    },
    //变更重组
    reorganize(name,data){
      let arr = [];
      for (const key in data) {
        let dataNew = data[key];
        Object.keys(dataNew).map((key)=>{
          if (key == name){
            arr.push(dataNew[key]);
            // console.log(dataNew[key])
          }
        });
      }
      return arr;
    },
  }
}
</script>

<style scoped>

</style>
